package data.platform.timescale.internal.command;

import data.platform.common.service.command.RulePointCommandService;
import data.platform.common.stream.aggregates.RulePoint;
import data.platform.common.util.DateUtil;
import data.platform.timescale.persistence.mapping.RulePointEO;
import data.platform.timescale.persistence.repository.TsRulePointRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Collections;

@ConditionalOnBean(name = "timeScaleConfig")
@Service
@Slf4j
@RequiredArgsConstructor
public class TsRulePointCommandServiceImpl implements RulePointCommandService {

    final TsRulePointRepository tsRulePointRepository;

    @Override
    public Mono<Integer> save(RulePoint rulePoint) {
        return Mono.just(rulePoint)
                .map(rp -> {
                    RulePointEO eo = new RulePointEO();
                    eo.setRuleId(rulePoint.getRuleId());
                    eo.setEventTime(DateUtil.getDateOfLocalDateTime(rp.getEventTime()));
                    eo.setHitNumber(rulePoint.getHitNumber());
                    eo.setHitData(rulePoint.getHitData());
                    return eo;
                })
                .flatMap(eo -> tsRulePointRepository.saveBatch(Collections.singleton(eo)));
    }
}
